<template>
  <div class="container" id="qrcover">
    <div class="cover-post" id="post-cover">
      <img :src="qrcodeImg" alt />
    </div>
    <!-- <div class="sub-title">
      好空气的还原者
    </div>-->
    <div class="qr-panel">
      <div v-if="nickname" class="user-info">
        <span class="user-name">{{ nickname }}</span>
        <span class="vip-level" v-if="vip_rule !== 0">{{ level }}</span>
      </div>
      <div v-if="code" class="invite-code">邀请码：{{ code }}</div>
      <div style="display:flex;">
        <img class="qrcode" :src="qrcode" alt />

        <div class="qrcode-info">
          <div class="tips">扫码注册 为爱分享</div>
          <div
            @click="showCanvas"
            v-if="!isGenerate"
            class="qrcode-btn"
            :style="{background:mainColor }"
          >生成图片</div>
        </div>
      </div>
    </div>
    <div v-if="imgUrl" @click="imgUrl = ''" class="img-cover">
      <img @click.stop :src="imgUrl" alt crossorigin="Anonymous" />
      <div class="qr-tips">长按保存图片</div>
    </div>
    <div v-if="arrowMask" @click.stop="arrowMask = false" class="arrow-mask">
      <img src="@/assets/商品分享-引导-assets/0.png" alt />
    </div>
  </div>
</template>

<script>
import QRCode from "qrcode";
import html2canvas from "html2canvas";
import { getUserInfo, getMyQrcode } from "@/api/profile";
import { mapState } from "vuex";
import wx from "weixin-js-sdk";
import { getWXSDK } from "@/api/wx";
export default {
  components: {},
  data() {
    return {
      nickname: "",
      level: "",
      code: "",
      qrcode: "",
      imgUrl: "",
      isGenerate: false,
      arrowMask: false,
      qrcodeImg: ""
    };
  },

  computed: {
    ...mapState({
      entryUrl: state => state.app.entryUrl,
      isMiniProgram: state => state.app.isMiniProgram,
      mainColor: state => state.app.mainColor,
      vip_rule: state => state.app.vip_rule
    })
  },

  watch: {},

  created() {
    this._getMyQrcode();
    if (this.vip_rule == 1) {
      getUserInfo({ code: this.$route.query.invite_code }).then(res => {
        if (res.status === 200) {
          this.nickname = res.data.data.nickname;
          this.level = res.data.data.level;
          this.code = res.data.data.code;
          QRCode.toDataURL(
            `${window.location.href.split("#")[0]}#/vip-invite?invite_code=${
              this.code
            }`
          )
            .then(url => {
              this.qrcode = url;
            })
            .catch(err => {
              console.error(err);
            });

          if (this.isMiniProgram) {
            let postData = {
              url:
                window.location.href.split("#")[0] +
                "static/redirect.html?app3Redirect=" +
                encodeURIComponent(
                  window.location.href.split("#")[0] +
                    "#" +
                    window.location.href.split("#")[1].split("?")[0] +
                    "?invite_code=" +
                    this.code
                ),
              title: this.nickname + "的邀请二维码"
            };
            wx.miniProgram.postMessage({ data: JSON.stringify(postData) });
          }
          //解决ios 签名失效问题
          let signLink = /(Android)/i.test(navigator.userAgent)
            ? location.href.split("#")[0]
            : this.entryUrl;
          getWXSDK({ shareurl: signLink }).then(res => {
            if (res.status === 200) {
              // console.log(res.data.data);
              let data = res.data.data;
              wx.config({
                debug: false,
                appId: data.appId, // 和获取Ticke的必须一样------必填，公众号的唯一标识
                timestamp: data.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.nonceStr, // 必填，生成签名的随机串
                signature: data.signature, // 必填，签名，见附录1
                jsApiList: ["onMenuShareAppMessage", "onMenuShareTimeline"]
              });
              //处理验证失败的信息
              wx.error(function(res) {
                // console.log("验证失败返回的信息:", res);
              });
              //处理验证成功的信息
              wx.ready(() => {
                // console.log("验证完成");
                this.onShare();
              });
            }
          });
        }
      });
    } else if (this.vip_rule == 0) {
      getUserInfo({ code: this.$route.query.invite_code }).then(res => {
        if (res.status === 200) {
          this.nickname = res.data.data.nickname;
          this.level = res.data.data.level;
          this.code = res.data.data.code;
          
          QRCode.toDataURL(
            `${window.location.href.split("#")[0]}#/vip-invite?invite_code=${
              this.code
            }`
          )
            .then(url => {
              this.qrcode = url;
            })
            .catch(err => {
              console.error(err);
            });

          if (this.isMiniProgram) {
            let postData = {
              url:
                window.location.href.split("#")[0] +
                "static/redirect.html?app3Redirect=" +
                encodeURIComponent(
                  window.location.href.split("#")[0] +
                    "#" +
                    window.location.href.split("#")[1].split("?")[0] +
                    "?invite_code=" +
                    this.code
                ),
              title: this.nickname + "的邀请二维码"
            };
            wx.miniProgram.postMessage({ data: JSON.stringify(postData) });
          }
          //解决ios 签名失效问题
          let signLink = /(Android)/i.test(navigator.userAgent)
            ? location.href.split("#")[0]
            : this.entryUrl;
          getWXSDK({ shareurl: signLink }).then(res => {
            if (res.status === 200) {
              // console.log(res.data.data);
              let data = res.data.data;
              wx.config({
                debug: false,
                appId: data.appId, // 和获取Ticke的必须一样------必填，公众号的唯一标识
                timestamp: data.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.nonceStr, // 必填，生成签名的随机串
                signature: data.signature, // 必填，签名，见附录1
                jsApiList: ["onMenuShareAppMessage", "onMenuShareTimeline"]
              });
              //处理验证失败的信息
              wx.error(function(res) {
                // console.log("验证失败返回的信息:", res);
              });
              //处理验证成功的信息
              wx.ready(() => {
                // console.log("验证完成");
                this.onShare();
              });
            }
          });
        }
      });
    }
  },
  updated() {
    // this.$nextTick(() => {
    //   const cover = document.querySelector('#post-cover')
    // cover.style.backgroundImage = `url(${this.qrcodeImg})`
    // cover.style.backgroundSize = 'cover'
    // cover.style.backgroundRepeat = 'no-repeat'
    // })
  },
  methods: {
    onShare() {
      let _this = this;
      let title = this.nickname + "的邀请二维码";
      let desc = this.nickname + "的邀请二维码";
      let imgUrl = this.qrcode;
      let link =
        window.location.href.split("#")[0] +
        "static/redirect.html?app3Redirect=" +
        encodeURIComponent(
          window.location.href.split("#")[0] +
            "#" +
            window.location.href.split("#")[1].split("?")[0] +
            "?invite_code=" +
            this.code
        );
      wx.onMenuShareAppMessage({
        title, // 分享标题
        desc, // 分享描述
        link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl, // 分享图标
        type: "link", // 分享类型,music、video或link，不填默认为link
        dataUrl: "", // 如果type是music或video，则要提供数据链接，默认为空
        success: res => {
          _this.arrowMask = false;
          this.$dialog.toast({
            mes: "分享成功",
            timeout: 1500,
            icon: "success"
          }); // 用户确认分享后执行的回调函数
          // console.log("分享给朋友成功返回的信息为:", res);
        },
        cancel: function(res) {
          _this.arrowMask = false;
          // 用户取消分享后执行的回调函数
          // console.log("取消分享给朋友返回的信息为:", res);
        }
      });

      //分享到朋友圈
      wx.onMenuShareTimeline({
        title, // 分享标题
        link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl, // 分享图标
        success: function(res) {
          _this.arrowMask = false;
          // 用户确认分享后执行的回调函数
          // console.log("分享到朋友圈成功返回的信息为:", res);
        },
        cancel: function(res) {
          _this.arrowMask = false;
          // 用户取消分享后执行的回调函数
          // console.log("取消分享到朋友圈返回的信息为:", res);
        }
      });
    },
    showCanvas() {
      window.pageYOffset = 0;
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      this.isGenerate = true;
      this.$nextTick(() => {
        html2canvas(document.querySelector("#qrcover"), {
          useCORS: true
          // allowTaint: true,//允许跨域图片
          // backgroundColor: null,
        }).then(canvas => {
          this.imgUrl = canvas.toDataURL("image/jpeg");
          this.isGenerate = false;
        });
      });
    },
    _getMyQrcode() {
      getMyQrcode()
        .then(res => {
          if (res.data.code === 200) {
            console.log(res);
            this.qrcodeImg = res.data.list[1].poster_cover;
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>
<style lang="less" scoped>
.container {
  // background-image: url("https://zhixiu-picture.oss-cn-shanghai.aliyuncs.com/1f38fa0ff564678f37aef2fe4988667d8a1e9628.jpg");
  // background-image: url("../../assets/kll/qr_bg.jpg");
  background-size: cover;
  background-position: 50% 50%;
  padding: 0 3%;
  .cover-post {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    img {
      width: 100%;
      object-fit: cover;
    }
  }
  .qrcode-title {
    text-align: center;
    margin-top: 3.2rem;
    img {
      height: 0.8rem;
    }
  }
  .sub-title {
    height: 1.4rem;
    line-height: 1.4rem;
    border-radius: 0.7rem;
    background: rgba(255, 255, 255, 0.28);
    font-size: 0.74rem;
    color: #086cfb;
    width: 10rem;
    margin: 0.4rem auto 0;
    text-align: center;
  }
  .qr-panel {
    position: absolute;
    left: 0;
    top: 674px;
    margin: 0 3%;
    box-sizing: border-box;
    // background-image: url("../../assets/kll/qrcode_panel.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    width: 94%;
    height: 10rem;
    padding: 0.9rem 2rem;
    .user-info {
      .user-name {
        color: #666;
        font-size: 0.72rem;
        font-weight: bold;
      }
      .vip-level {
        color: #fa8e02;
        border: 0.02rem solid #fa8e02;
        border-radius: 0.2rem;
        padding: 0.1rem;
        font-size: 0.52rem;
        text-align: center;
        display: inline-block;
        min-width: 2.8rem;
        margin-left: 0.8rem;
      }
    }
    .invite-code {
      color: #fa8e02;
      font-size: 0.52rem;
      line-height: 0.52rem;
      padding: 0.6rem 0;
    }
    .qrcode {
      width: 4.4rem;
      height: 4.4rem;
    }
    .tips {
      color: #666;
      font-size: 0.56rem;
      text-align: center;
      padding: 0.9rem 0;
    }
    .qrcode-info {
      width: calc(100% - 4.4rem);
      text-align: center;
      padding-left: 0.8rem;
    }
    .qrcode-btn {
      width: 5.2rem;
      background: #93df4a;
      height: 1.4rem;
      border-radius: 0.7rem;
      line-height: 1.4rem;
      font-size: 0.68rem;
      text-align: center;
      color: #fff;
      font-weight: 500;
    }
  }
  .img-cover {
    background: rgba(0, 0, 0, 0.5);
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    text-align: center;
    img {
      margin-top: 8vh;
      width: 12rem;
    }
    .qr-tips {
      margin-top: 0.48rem;
      font-size: 0.48rem;
      color: #fff;
    }
  }
  .arrow-mask {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    text-align: right;
    z-index: 99999;
    img {
      margin-right: 9%;
    }
  }
}
</style>
